from django.shortcuts import render,HttpResponse,redirect
from django.core.paginator import Paginator
from .models import *

# Create your views here.
#添加
def add(request):
    if request.method=='GET':
        return render(request,'add.html')
    if request.method=='POST':
        title = request.POST.get('title')
        Qtype = request.POST.get('Qtype')
        option1 = request.POST.get('option1')
        option2 = request.POST.get('option2')
        option3 = request.POST.get('option3')
        option4 = request.POST.get('option4')
        answer = request.POST.get('answer')
        CreatTime=request.POST.get('CreatTime')
        NowTime=request.POST.get('NowTime')
        quest=Question(title=title,Qtype=Qtype,option1=option1,
                       option2=option2,option3=option3,option4=option4,
                       answer=answer,CreatTime=CreatTime,NowTime=NowTime)
        quest.save()
        return redirect('show')
#展示所有
def show(request):
    page = Question.objects.all()  # 先获取所有值
    pag = request.GET.get('pag')  # 给pag传递值
    paginator = Paginator(page, 3)  # 给page分页,确定一页有几个
    Nowpage = paginator.get_page(pag)  # 当前页
    currentpage = Nowpage.number  # 当前页数字
    last_page = currentpage - 1  # 上一页
    next_page = currentpage + 1  # 下一页
    max_page = paginator.num_pages  # 1最大页
    small_page = 1
    if currentpage == max_page:
        next_page = max_page
    if currentpage == small_page:
        last_page = small_page
    return render(request, 'show.html', context={'page': page, 'Nowpage': Nowpage, 'currentpage': currentpage,
                                                    'last_page': last_page, 'next_page': next_page,
                                                    'max_page': max_page})
#删除
def dele(request,id):
    quion = Question.objects.get(id=id)
    quion.delete()
    return redirect('show')
#修改
def amend(request,id):
    if request.method=='GET':
        geng=Question.objects.get(id=id)
        return render(request,'amend.html')
    if request.method=='POST':
        title = request.POST.get('title')
        Qtype = request.POST.get('Qtype')
        option1 = request.POST.get('option1')
        option2 = request.POST.get('option2')
        option3 = request.POST.get('option3')
        option4 = request.POST.get('option4')
        answer = request.POST.get('answer')
        geng = Question.objects.get(id=id)
        geng.title=title
        geng.Qtype=Qtype
        geng.option1 = option1
        geng.option2 = option2
        geng.option3 = option3
        geng.option4 = option4
        geng.answer = answer
        geng.save()
        return redirect('show')
#搜索
def search(request):
    if request.method == 'GET':
        return render(request,'sou.html')
    if request.method == 'POST':
        title=request.POST.get('title')
        question=Question.objects.filter(title__contains=title)
        return render(request,'suo.html',{'question':question})
# 分页









